package com.zyh.system.supermark1.dao.impl;

import com.zyh.system.supermark1.dao.BuyCarDao;
import com.zyh.system.supermark1.db.BaseDAO;
import com.zyh.system.supermark1.domain.BuyCar;
import com.zyh.system.supermark1.domain.User;

import java.util.List;

public class BuyCarDaoImpl implements BuyCarDao {
    // 根据购物车 id 查询单条信息
    @Override
    public List<BuyCar> selectByBuyCarId(String buyCayId) {
        String sql = "select * from buycar where id=?";
        return BaseDAO.selectData(sql, BuyCar.class, buyCayId);
    }

    /**
     * 向购物车添加商品对象
     *
     * @param
     */
    @Override
    public int add(BuyCar buyCar) {
        List<BuyCar> buyCarList = selectByBuyCarId(buyCar.getId());
        if (buyCarList.size() == 0) {// 购物车中没有相同 id 的商品
            String sql = " insert into buycar value (?,?,?,?)";
            return BaseDAO.changeOneData(sql, buyCar.getId(), buyCar.getName(), buyCar.getPrice(), buyCar.getBuyNum());
        } else {// 购物车中有相同 id 的商品
            Integer buyNum = BaseDAO.selectData("select buyNum from buycar where id=?", BuyCar.class, buyCar.getId()).get(0).getBuyNum();
            String sql = " update buycar set buyNum=? where id=?";
            return BaseDAO.changeOneData(sql, buyNum + buyCar.getBuyNum(), buyCar.getId());
        }
    }

    /**
     * 展示购物车所有信息
     */
    @Override
    public List<BuyCar> showBuyCar() {
        String sql = "select * from buycar";
        return BaseDAO.selectData(sql, BuyCar.class);
    }

    /**
     * 清空购物车
     */
    @Override
    public void clearBuyCar(List<BuyCar> buyCars) {
        String sql = "truncate buycar";
        BaseDAO.changeOneData(sql);
    }

    /**
     * 展示用户信息
     *
     * @param user 用户登录的信息对象
     */
    @Override
    public User showUserInfo(User user) {
        String sql = "select * from user where id=?";
        List<User> users = BaseDAO.selectData(sql, User.class, user.getId());
        if (users.size() != 0) {
            return users.get(0);
        }
        return null;
    }
}
